import java.util.Random;

public class ThreadBlock {
    static class MyBlockedQueue{
        private int first;
        private int last;
        private int size;
        private int[] items;
        public MyBlockedQueue(int capaCity){
            this.first=0;
            this.size=0;
            this.last=0;
            this.items=new int[capaCity];
        }
        public  void offer(int val) throws InterruptedException {
            synchronized (this){
                if(size==items.length){
                    this.wait();
                }
                items[last]=val;
                first++;
                size++;
                if(last==items.length){
                    last=0;
                }
                this.notify();
            }
        }
        public int poll() throws InterruptedException {
            int result=0;
            synchronized (this){
                if(size==0){
                    this.wait();
                }
                result=items[first];
                first++;
                size--;
                if(first==items.length){
                    first=0;
                }
                this.notify();
            }
            return result;
        }
    }

    public static void main(String[] args) {
        MyBlockedQueue myBlockedQueue=new MyBlockedQueue(10);
        Thread t1=new Thread(()->{
            while(true){
                int num=new  Random().nextInt(10);
                try {
                    System.out.println("添加数据："+num);
                    myBlockedQueue.offer(num);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread t2=new Thread(()->{
            while(true){
                try{
                    int result=myBlockedQueue.poll();
                    System.out.println("消费数据："+result);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

            }
        });
        t2.start();
    }
}
